<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <!-- 引入react核心库 -->
    <script type="text/javascript" src="../../js/react17/react.development.js"></script>
    <!-- 用于支持react操作DOM -->
    <script type="text/javascript" src="../../js/react17/react-dom.development.js"></script>
    <!-- 用于将jsx转为js -->
    <script type="text/javascript" src="../../js/react17/babel.min.js"></script>
    <!-- 用于对组件标签属性进行限制 -->
    <script type="text/javascript" src="../../js/react17/prop-types.js"></script>
</head>
<body>
    <div id="test"></div>

    <script type="text/babel">
        class MyComponent extends React.Component{
            state = {newsArr: []}
            // 每隔1s将1条新闻插入列表
            componentDidMount(){
                setInterval(()=>{
                    // 获取新闻列表
                    let {newsArr} = this.state
                    // 模拟一条新闻
                    const news = "新闻" + (newsArr.length+1)
                    // 将新闻插入状态
                    this.setState({newsArr: [news,...newsArr]})
                },1000)
            }
            // 得到未更新前的内容高度
            getSnapshotBeforeUpdate(){
                return this.refs.list.scrollHeight
            }
            // scrollTop固定在当前页面上
            componentDidUpdate(preProps,preState,height){
                this.refs.list.scrollTop += this.refs.list.scrollHeight - height
            }
            
            // 渲染新闻列表
            render(){
                return (
                    <div className="newsList" ref="list">
                        {
                            this.state.newsArr.map((n,index)=>{
                                return (
                                    <div key={index} className="news">{n}</div>
                                )
                            })
                        }
                    </div>
                )
            }
        }
       
        let p ={}
        ReactDOM.render(<MyComponent {...p}/>,document.getElementById("test"))
    </script>
</body>
<style>
.newsList{
    width: 200px;
    height: 150px;
    background-color: cadetblue;
    overflow: auto;
}
.news{
    height: 30px;
}
</style>
</html>